<?php
require_once 'db/db.php';

function deletePost( $threadNum, $postNum ) {
  try {
    // XXX deleteing all posts will leave hanging thread
    if( postCount($threadNum) < 2 ) {
      // XXX Modify to link post MIN(post.rank) to thread
      die("Please Delete Thread Instead");
    }
    $db = openDbConn();
    $db->beginTransaction();
    $db->exec("DELETE FROM post WHERE post.tid = $threadNum AND post.rank = $postNum;");
    $db->commit();
  } catch ( PDOException $e ) {
    $db->rollback();
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}

// int -> int -> string -> string -> bool
function setPost( $threadNum, $postNum, $title, $datum, $options ) {
  try {
    $uid = (isset($_SESSION['uid'])) ? $_SESSION['uid'] : 0;
    $mode = (is_string($options['mode'])) ? $options['mode'] : "none";
    $time = time();

    $db = openDbConn();

    $title = $db->quote($title);
    $datum = $db->quote($datum);
    $mode = $db->quote($mode);

    $db->beginTransaction();
    // create thread for post -1
    if ( $postNum > 0 ) {  
      $db->exec("UPDATE post 
                                    SET name = $title, 
                                        datum = $datum,
                                        date = $time 
                                    WHERE rank = $postNum
                                      AND tid = $threadNum;");
    } elseif ( $postNum == 0 ) {
      $db->exec("INSERT INTO thread (fid, mode, rank) 
                                    VALUES ( ${threadNum}, $mode, 0 );
                                  INSERT INTO post (tid, uid, rank, name, datum, date) 
                                    VALUES( (SELECT MAX(id) FROM thread), 
                                            $uid,
                                            1 + COALESCE( (SELECT MAX(rank) FROM post
                                                             WHERE tid = (SELECT MAX(id) FROM thread ) ),
                                                      0 ), 
                                            $title, 
                                            $datum,
                                            $time);");
    } elseif ( $postNum < 0 ) {
      $db->exec("INSERT INTO post (tid, uid, rank, name, datum, date) 
                                    VALUES( ${threadNum}, 
                                            $uid,
                                            1+ COALESCE( (SELECT MAX(rank) FROM post
                                                             WHERE tid = (SELECT MAX(id) FROM thread ) ),
                                                      0), 
                                            $title, 
                                            $datum,
                                            $time);");     
    }
    $db->commit();
  } catch ( PDOException $e ) {
    $db->rollback();
    print 'ERROR: ' . $e->getMessage() . '<br />';
    die();
  }
}
?>
